package com.jt.common.thread;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.CopyOnWriteArrayList;

public class SyncTests {
    //private static List<String> cache = new ArrayList<>();
//    private static List<String> cache = new Vector<>();
    //CopyOnWriteArrayList是一个线程安全的List集合,允许多个线程执行并发更新,但是只能有一个更新成功.==>调用CPU的SAC算法
    private static List<String> cache = new CopyOnWriteArrayList<>();
    public static  List<String> selectAll(){
        if (cache.isEmpty()){
            synchronized (cache){
                if (cache.isEmpty()){
                    System.out.println("====Get Data From Databases====");
                    List<String> data = Arrays.asList("A","B","C");
                    cache.addAll(data);
                }
            }
        }
        return cache;
    }

    public static void main(String[] args) {
        Thread thread1 = new Thread() {
            public void run(){
                System.out.println(selectAll());
            }
        };
        Thread thread2 = new Thread() {
            public void run(){
                System.out.println(selectAll());
            }
        };
        Thread thread3 = new Thread() {
            public void run(){
                System.out.println(selectAll());
            }
        };
        Thread thread4 = new Thread() {
            public void run(){
                System.out.println(selectAll());
            }
        };
        Thread thread5 = new Thread() {
            public void run(){
                System.out.println(selectAll());
            }
        };
        Thread thread6 = new Thread() {
            public void run(){
                System.out.println(selectAll());
            }
        };
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
        thread5.start();
        thread6.start();
    }
}
